import * as step from '@flow-step/step-toolkit'
import path from 'path'
import fs from 'fs'

export async function setup(flowJobToken: string, npmPrivateRepoConfigPath: string): Promise<void> {
    try {
        const npmPrivateRepoConfigPathDir = path.dirname(npmPrivateRepoConfigPath)
        fs.mkdirSync(npmPrivateRepoConfigPathDir as string, {recursive: true})
        step.exportEnvVar('NPM_PRIVATE_REPO_CONFIG_PATH', npmPrivateRepoConfigPath)
        step.info(`export NPM_PRIVATE_REPO_CONFIG_PATH=${npmPrivateRepoConfigPath}`)

        const npmPrivateRepoCertificate = await step.certificate.getNpmPrivateRepoCertificate(flowJobToken)
        if (npmPrivateRepoCertificate === undefined || npmPrivateRepoCertificate.npmRepoConfigContent === undefined) {
            throw new Error(`NPM private repo config content is empty`)
        }

        fs.writeFileSync(npmPrivateRepoConfigPath, npmPrivateRepoCertificate.npmRepoConfigContent)
        step.info(`save npmPrivateRepoCertificate to ${npmPrivateRepoConfigPath} successfully!`)
    } catch (e) {
        step.error(`setup npm private repo config failed: ${e}`)
        throw e;
    }
}
